package com.library.servlet;

import com.library.util.DBUtil;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.json.JSONObject;

@WebServlet("/api/returnBook")
public class ReturnBookServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String idStr = request.getParameter("id");
        JSONObject jsonResponse = new JSONObject();

        try {
            int id = Integer.parseInt(idStr);
            try (Connection conn = DBUtil.getConnection()) {
                String sql = "UPDATE borrow_records SET status = 'returned', return_date = NOW() WHERE id = ?";
                try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                    stmt.setInt(1, id);
                    int result = stmt.executeUpdate();
                    if (result > 0) {
                        jsonResponse.put("success", true);
                        jsonResponse.put("message", "还书成功");
                    } else {
                        jsonResponse.put("success", false);
                        jsonResponse.put("message", "还书失败");
                    }
                }
            }
        } catch (Exception e) {
            jsonResponse.put("success", false);
            jsonResponse.put("message", "参数错误或系统异常");
        }

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(jsonResponse.toString());
    }
} 